package com.videoaggre.zcl.ui.activity.agefans

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.kingja.loadsir.core.LoadService
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.videoaggre.zcl.R
import com.videoaggre.zcl.bean.AgefansPage
import com.videoaggre.zcl.common.showEmptyCallback
import com.videoaggre.zcl.common.showLoadingCallback
import com.videoaggre.zcl.helper.loadsir.LoadSirHelper
import com.videoaggre.zcl.ui.activity.BaseActivity
import com.videoaggre.zcl.ui.adapter.BaseRecyclerAdapter
import com.videoaggre.zcl.utils.Logger
import kotlinx.android.synthetic.main.activity_base_refresh.*

abstract class AgefansBaseRefreshActivity<T>(layoutResID: Int? = null) : BaseActivity(layoutResID ?: R.layout.activity_base_refresh) {
    protected val mLoadService: LoadService<*> by lazy { createLoadService() }
    protected lateinit var mBaseRecyclerAdapter: BaseRecyclerAdapter<*, T>
    protected var mAgefansPage = AgefansPage<T>()
    override fun initView() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = mBaseRecyclerAdapter
        refreshLayout.setOnRefreshListener(::onRefresh)
        refreshLayout.setOnLoadMoreListener(::onLoadMore)
    }

    open fun createLoadService(): LoadService<*> = LoadSirHelper.register(refreshLayout) { onReload() }
    override fun initData() {
        mLoadService.showLoadingCallback()
        onReload()
    }

    protected fun onRefresh(refreshLayout: RefreshLayout?) {
        mAgefansPage.currentPage = 1
        onReload()
    }

    protected fun onLoadMore(refreshLayout: RefreshLayout?) {
        mAgefansPage.currentPage++
        onReload()
    }

    abstract fun onReload()
    fun handResult(agefansPage: AgefansPage<T>) {
        runOnUiThread {
            kotlin.runCatching {
                mAgefansPage = agefansPage
                Logger.e(mAgefansPage.toString())
                if (1 == mAgefansPage.currentPage) {
                    if (mAgefansPage.data.isEmpty()) {
                        mLoadService.showEmptyCallback()
                    }
                    mBaseRecyclerAdapter.datas = mAgefansPage.data
                    mBaseRecyclerAdapter.notifyDataSetChanged()
                } else {
                    mLoadService.showSuccess()
                    mBaseRecyclerAdapter.addAll(mAgefansPage.data)
                }
                if (mAgefansPage.currentPage == mAgefansPage.totalPage) {
                    refreshLayout.setNoMoreData(true)
                } else {
                    refreshLayout.setNoMoreData(false)
                }
            }
        }
    }
}